package code.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * <p>description: ehcache缓存工具类
 *    SINGER_SONG_SEARCH是配置在ehcache.xml中的cacheName
 * </p>
 *
 * @author chenrui
 * @since 2018-12-01
 */
public class SingerSongEhcacheUtil {

    private static CacheManager cacheManager = CacheManager.create();

    private static final String SINGER_SONG_SEARCH = "singer_song_cache";

    public static Object get(Object key) {
        Cache cache = cacheManager.getCache(SINGER_SONG_SEARCH);
        if(cache!= null) {
            Element element = cache.get(key);
            if(element != null) {
                return element.getObjectValue();
            }
        }
        return null;
    }

    public static void put(Object key, Object value) {
        Cache cache = cacheManager.getCache(SINGER_SONG_SEARCH);
        if (cache != null) {
            cache.put(new Element(key, value));
        }
    }

    public static boolean remove(Object key) {
        Cache cache = cacheManager.getCache(SINGER_SONG_SEARCH);
        if (cache != null) {
            return cache.remove(key);
        }
        return false;
    }

    public static void main(String[] args) {
        String key = "key";
        String value = "hello";
        SingerSongEhcacheUtil.put(key, value);
        SingerSongEhcacheUtil.get(key);
    }

}
